package cn.symbio.basic.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.io.File;

@Component
public class EmailUtils {

    // 注入邮件对象
    @Autowired
    private  JavaMailSender javaMailSender;

    private static EmailUtils emailUtils;

    /**
     * 初始化对象
     */
    @PostConstruct
    public void init() {
        emailUtils = this;
        emailUtils.javaMailSender = this.javaMailSender;
    }

    /**
     *
     * @param sender 发件人
     * @param title 标题
     * @param text 内容
     * @param recipients  收件人
     * @param accessoryName 附件名
     * @param URL 附件图片路径
     * @throws MessagingException
     */
    public static void sendEmail(String sender,String title,String text,String recipients,String accessoryName,String URL) throws MessagingException {
        // 1.创建复杂邮件对象
        MimeMessage mimeMessage = emailUtils.javaMailSender.createMimeMessage();
        // 2.发送复杂邮件的工具类
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true,"utf-8");
        helper.setFrom(sender);
        helper.setSubject(title);
        // 3.设置文本内容，第二个参数 true 代表是否是一个html内容
        helper.setText(text,true);
        // 4.添加附件
        helper.addAttachment(accessoryName,new File(URL));
        // 5.设置收件人
        helper.setTo(recipients);
        // 6.发送邮件
        emailUtils.javaMailSender.send(mimeMessage);
    }
    /**
     *
     * @param sender 发件人
     * @param title 标题
     * @param text 内容
     * @param recipients  收件人
     * @throws MessagingException
     */
    public static void sendEmail(String sender,String title,String text,String recipients) throws MessagingException {
        // 1.创建复杂邮件对象
        MimeMessage mimeMessage = emailUtils.javaMailSender.createMimeMessage();
        // 2.发送复杂邮件的工具类
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true,"utf-8");
        helper.setFrom(sender);
        helper.setSubject(title);
        // 3.设置文本内容，第二个参数 true 代表是否是一个html内容
        helper.setText(text,true);
        // 4.设置收件人
        helper.setTo(recipients);
        // 5.发送邮件
        emailUtils.javaMailSender.send(mimeMessage);
    }
}
